package org.jeecg.modules.clue.job;

import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.mail.Mail;
import cn.hutool.extra.mail.MailAccount;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.modules.clue.entity.ClueBatchQuery;
import org.jeecg.modules.clue.entity.ClueRecordTask;
import org.jeecg.modules.clue.entity.ClueTaskQueryLog;
import org.jeecg.modules.clue.enums.BatchQueryStatStatus;
import org.jeecg.modules.clue.enums.ClueQueryStatus;
import org.jeecg.modules.clue.enums.ClueQueryTriggerType;
import org.jeecg.modules.clue.enums.TaskPushStatus;
import org.jeecg.modules.clue.service.IClueBatchQueryService;
import org.jeecg.modules.clue.service.IClueRecordTaskService;
import org.jeecg.modules.clue.service.IClueTaskQueryLogService;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 示例带参定时任务
 *
 * @Author Scott
 */
@Slf4j
@Component
@DisallowConcurrentExecution
public class ClueTaskQueryJob implements Job {

    /**
     * 若参数变量名修改 QuartzJobController中也需对应修改
     */
    private String parameter;

    public void setParameter(String parameter) {
        this.parameter = parameter;
    }

    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    IClueBatchQueryService clueBatchQueryService;
    @Resource
    IClueRecordTaskService clueRecordTaskService;
    @Resource
    IClueTaskQueryLogService clueTaskQueryLogService;
    @Resource(name = "clueMailAccount")
    private MailAccount mailAccount;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info("ClueTaskQueryJob 定时任务");
        // 查询系统里面，推送成功的、近30天的任务
        Date currentDay = new Date();
        Date previousMonthDay = DateUtil.offsetMonth(currentDay, -1);
        List<ClueRecordTask> taskList = clueRecordTaskService.list(new LambdaQueryWrapper<ClueRecordTask>()
                .eq(ClueRecordTask::getPushStatus, TaskPushStatus.推送成功.status)
                .between(ClueRecordTask::getCreateTime, previousMonthDay, currentDay)
        );
        if (taskList.isEmpty()) {
//			log.info("未查询到推送成功、近30天的任务");
            return;
        }

        log.info("近30天推送成功的task {}", JSON.toJSONString(taskList));
        // 批量查询记录
        ClueBatchQuery batchQuery = new ClueBatchQuery();
        batchQuery.setBatchNo(Objects.requireNonNull(FillRuleUtil.executeRule("clue_batch_query_rule", (JSONObject) JSON.toJSON(batchQuery))).toString());
        batchQuery.setQueryTotal(BigDecimal.valueOf(taskList.size()));
        batchQuery.setStatStatus(BatchQueryStatStatus.未统计.status);
        clueBatchQueryService.save(batchQuery);


        // 生成待查询日志
        List<ClueTaskQueryLog> logList = taskList.stream().map(new Function<ClueRecordTask, ClueTaskQueryLog>() {
            @Override
            public ClueTaskQueryLog apply(ClueRecordTask clueRecordTask) {
                ClueTaskQueryLog clueTaskQueryLog = new ClueTaskQueryLog();
                BeanUtils.copyProperties(clueRecordTask, clueTaskQueryLog, "id", "remark");
                clueTaskQueryLog.setQueryLogNo(Objects.requireNonNull(FillRuleUtil.executeRule("clue_batch_query_rule", (JSONObject) JSON.toJSON(clueTaskQueryLog))).toString());
                clueTaskQueryLog.setBatchQueryNo(batchQuery.getBatchNo());
                clueTaskQueryLog.setQueryStatus(ClueQueryStatus.待查询.status);
                clueTaskQueryLog.setTriggerType(ClueQueryTriggerType.定时任务.status);
                return clueTaskQueryLog;
            }
        }).collect(Collectors.toList());
        clueTaskQueryLogService.saveBatch(logList);

        // mq操作
        ZSetOperations<String, String> opsForZSet = stringRedisTemplate.opsForZSet();
        opsForZSet.add(ClueBatchQueryListener.Topic, batchQuery.getBatchNo(), 2000);
        log.info("将 batchNo {} 推送到 {}", batchQuery.getBatchNo(), ClueBatchQueryListener.Topic);


        String send = Mail.create(mailAccount)
                .setTos(mailAccount.getUser())
                .setTitle("定时查询线索任务状态通知")
                .setContent(String.format("查询时间:%s  批次查询记录号:%s", DateUtils.now(), batchQuery.getBatchNo()))
                .send();
        log.info("邮件发送结果 {}", send);

//		TODO 客户通知
    }


}
